<?php
defined('_VALID_MOS') or die('Direct Access to this location is not allowed.');
/**
*
* Version : 2.1
* ID      : ptype shipping module
* Author  : Adam Hughes
* Site    : www.questtech.co.uk
* License : Free
*
*/

/**
* 
*
* This class will allow you to set up a minimum rate for free shipping
* a rate for anything under the minimum rate
* Also a 'bypass type(s)' which allows for any a set rate if any 
* items in a particular type are in the order
* @copyright (C) 2006 Adam Hughes
* 
*******************************************************************************
*/

		
class ptype {

	var $classname = "ptype";

	function list_rates( &$d ) {
		global $total, $tax_total, $CURRENCY_DISPLAY, $vmLogger;
		$db =& new ps_DB;
		$dbv =& new ps_DB;

		$cart = $_SESSION['cart'];

		/** Read current Configuration ***/
		require_once(CLASSPATH ."shipping/".$this->classname.".cfg.php");
	
		if ( $_SESSION['auth']['show_price_including_tax'] != 1 ) {
			$taxrate = 1;
			$order_total = $total + $tax_total;
		}
		else {
			$taxrate = $this->get_tax_rate() + 1;
			$order_total = $total;
		}
		
		//Charge minimum up to this value in cart
		$base_ship = ptype_BASE_AMOUNT;

		//Flat rate shipping charge up to minimum value
		$max_charge = ptype_MAX_CHG;
		
		//Flat rate shipping charge above minimum value
		$min_charge = ptype_MIN_CHG;
		
		//Charge to be applied to an invoice that has an item from the bypass group
		$bypass_amount = ptype_BYPASS_AMOUNT;
		
		//Bypass product group
		$bypass_group = ptype_BYPASS_GROUP;
		
		//Now create a comma delimited list of products from the order (which is used to query the db)	
		for ($i=0; $i < $cart[idx]; $i++)
			{
				if ($i != 0) $q .= ",";
				$q .= $cart[$i]["product_id"];
			}
		//Now Create the sql to query the database to check for products in the bypass groups
		$sqltorun = "SELECT product_type_id from";
		//DB ADH : $sqltorun .= " (SELECT product_type_id from #__{vm}_product_product_type_xref as a WHERE product_id in (";
		$sqltorun .= " (SELECT product_type_id from #__{vm}_product_product_type_xref as a WHERE product_id in (";
		$sqltorun .= $q;
		$sqltorun .= ")) b WHERE product_type_id in (";
		$sqltorun .= $bypass_group;
		$sqltorun .= ")";
		$vmLogger->debug( "PTYPE Shipping Module: Generated Sql for product check is : {$sqltorun}" );

	//Now we check (using the vm db layer if any of the products are in the bypass group
	require_once( CLASSPATH. 'ps_database.php' );
	$db->query("{$sqltorun}");	
	//If the query has any record then set the shipping value
	if ($db->next_record()) 
		{
			$vmLogger->debug( "PTYPE Shipping Module: I have found products in the bypass group(s)");
			$shipping_rate_id = urlencode($this->classname."|STD|Standard Shipping over ".$base_ship."|".$bypass_amount);
			$html = "";
			$html .= "\n<input type=\"radio\" name=\"shipping_rate_id\" id=\"ptype_shipping_rate\" checked=\"checked\" value=\"$shipping_rate_id\" />\n";
			$html .= "<label for=\"ptype_shipping_rate\">Standard Shipping: ";
			$html .= $CURRENCY_DISPLAY->getFullValue($bypass_amount);
			$html .= "</label>";
			$_SESSION[$shipping_rate_id] = 1;
		}
			//Now if it wasn't in the bypass group (i.e. check it $html has already been set)
			if (empty($html))
				{
					$vmLogger->debug( "PTYPE Shipping Module: I haven't found any products in the bypass group(s)" );
					if($order_total < $base_ship)
						{
						$vmLogger->debug( "PTYPE Shipping Module: No products in the bypass group(s) and order total is less than base shipment");
						$max_charge *= $taxrate;
						$shipping_rate_id = urlencode($this->classname."|STD|Standard Shipping under ".$base_ship."|".$max_charge);
						$html = "";
						$html .= "\n<input type=\"radio\" name=\"shipping_rate_id\" checked=\"checked\" id=\"ptype_shipping_rate\" value=\"$shipping_rate_id\" />\n";
						$html .= "<label for=\"ptype_shipping_rate\">Standard Shipping: ";
						$html .= $CURRENCY_DISPLAY->getFullValue($max_charge);
						$html .= "</label>";
						$_SESSION[$shipping_rate_id] = 1;
						}
					else
						{
						$vmLogger->debug( "PTYPE Shipping Module: No products in the bypass group(s) and order total is more than base shipment");
						$min_charge *= $tax_rate;
						$shipping_rate_id = urlencode($this->classname."|STD|Standard Shipping over ".$base_ship."|".$min_charge);
						$html = "";
						$html .= "\n<input type=\"radio\" name=\"shipping_rate_id\" id=\"ptype_shipping_rate\" checked=\"checked\" value=\"$shipping_rate_id\" />\n";
						$html .= "<label for=\"ptype_shipping_rate\">Standard Shipping: ";
						$html .= $CURRENCY_DISPLAY->getFullValue($min_charge);
						$html .= "</label>";
						$_SESSION[$shipping_rate_id] = 1;
						}
					}
		echo $html;
		return true;

	}

	function get_rate( &$d ) {

		$shipping_rate_id = $d["shipping_rate_id"];
		$is_arr = explode("|", urldecode(urldecode($shipping_rate_id)) );
		$order_shipping = $is_arr[3];
		return $order_shipping;

	}
	
		
	function get_tax_rate() {

		/** Read current Configuration ***/
		require_once(CLASSPATH ."shipping/".$this->classname.".cfg.php");

		if( intval(ptype_TAX_CLASS)== 0 )
		return( 0 );
		else {
			require_once( CLASSPATH. "ps_tax.php" );
			$tax_rate = ps_tax::get_taxrate_by_id( intval(ptype_TAX_CLASS) );
			return $tax_rate;
		}
	}
	
	/* Validate this Shipping method by checking if the SESSION contains the key
	* @returns boolean False when the Shipping method is not in the SESSION
	*/
	function validate( $d ) {

		$shipping_rate_id = $d["shipping_rate_id"];

		if( array_key_exists( $shipping_rate_id, $_SESSION )) {
			
			return true;
		}
		else {
			return false;
		}
	}
	/**
    * Show all configuration parameters for this Shipping method
    * @returns boolean False when the Shipping method has no configration
    */
	function show_configuration() {
		global $VM_LANG;
		/** Read current Configuration ***/
		require_once(CLASSPATH ."shipping/".$this->classname.".cfg.php");
    ?>
      <table>
    <tr>
        <td><strong>Amount for minimum shipping charge :</strong></td>
		<td>
            <input type="text" name="ptype_BASE_AMOUNT" class="inputbox" value="<?php echo ptype_BASE_AMOUNT ?>" />
		</td>
		<td>
        <?php echo mm_ToolTip("A flat fee will be charged if the total value of the cart is less than this amount. If the value of the cart is greater than the amount is zero") ?> 
        </td>
    </tr>
    <tr>
        <td><strong>Maximum Shipping Charge:</strong>		</td>
		<td>
            <input type="text" name="ptype_MAX_CHG" class="inputbox" value="<?php echo ptype_MAX_CHG ?>" />
		</td>
		<td>
        <?php echo mm_ToolTip("This is the flat fee to be charged if the value in the cart is less than the amount entered above.") ?>
        </td>
    </tr>
    <tr>
        <td><strong>Minimum Shipping Charge:</strong></td>
		<td>
            <input type="text" name="ptype_MIN_CHG" class="inputbox" value="<?php echo ptype_MIN_CHG ?>" />
		</td>
		<td>
        <?php echo mm_ToolTip("This is the flat fee to be charged if the value in the cart is more than the amount entered above.") ?>
        </td>
    </tr>
	<tr>
		<td>
			<b>Bypass Product Shipping Charge</b>
		</td>
		<td>
            <input type="text" name="ptype_BYPASS_AMOUNT" class="inputbox" value="<?php echo ptype_BYPASS_AMOUNT ?>" />
		</td>
		<td>
        <?php echo mm_ToolTip("This is the flat fee to be charged if the cart has an item from the bypass group.") ?>
        </td>
	</tr>
	  <tr>
	  	<td>
			<strong>Bypass Product Group</strong>
		</td>
		<td>
			<input type="text" name="ptype_BYPASS_GROUP" class="inputbox" value="<?php echo ptype_BYPASS_GROUP ?>" />
		</td>
		<td>
			<?php echo mm_ToolTip("Enter the group you wish to override the shipping This can be a comma delimited list if you wish to include more than one group") ?>
		</td>
		</tr>
		<tr>
			<td>
				<strong><?php echo $VM_LANG->_PHPSHOP_UPS_TAX_CLASS ?></strong></td>
			<td>
		  		<?php require_once(CLASSPATH.'ps_tax.php');
				ps_tax::list_tax_value("PTYPE_TAX_CLASS", PTYPE_TAX_CLASS) ?>
			</td>
			<td>
				<?php echo mm_ToolTip($VM_LANG->_PHPSHOP_UPS_TAX_CLASS_TOOLTIP) ?>
			<td>
	  </tr>	

	</table>
   <?php
   // return false if there's no configuration
   return true;
	}
	/**
  * Returns the "is_writeable" status of the configuration file
  * @param void
  * @returns boolean True when the configuration file is writeable, false when not
  */
	function configfile_writeable() {
		return is_writeable( CLASSPATH."shipping/".$this->classname.".cfg.php" );
	}

	/**
	* Writes the configuration file for this shipping method
	* @param array An array of objects
	* @returns boolean True when writing was successful
	*/
	function write_configuration( &$d ) {
	    global $vmLogger;

		$my_config_array = array("ptype_BASE_AMOUNT" => $d['ptype_BASE_AMOUNT'],
		"ptype_MIN_CHG" => $d['ptype_MIN_CHG'],
		"ptype_MAX_CHG" => $d['ptype_MAX_CHG'],
		"ptype_BYPASS_AMOUNT" => $d['ptype_BYPASS_AMOUNT'],
		"ptype_BYPASS_GROUP" => $d['ptype_BYPASS_GROUP'],
		"ptype_TAX_CLASS" => $d['ptype_TAX_CLASS']
		);
		$config = "<?php\n";
		$config .= "defined('_VALID_MOS') or die('Direct Access to this location is not allowed.'); \n\n";
		foreach( $my_config_array as $key => $value ) {
			$config .= "define ('$key', '$value');\n";
		}

		$config .= "?>";

		if ($fp = fopen(CLASSPATH ."shipping/".$this->classname.".cfg.php", "w")) {
			fputs($fp, $config, strlen($config));
			fclose ($fp);
			return true;
		}
		else {
			$vmLogger->err( "Error writing to configuration file" );
			return false;
		}
	}
}


?>
